package com.example.ffepeg.ffmTestIng;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class TestFiles {
    public static void main(String[] args) {
        DownloadByUrl("https://v.douyin.com/iPHQqLj7/");
    }
    //file_url-文件下载链接
    public static void DownloadByUrl(String file_url){
        String res = "ERR";
        int bytesum = 0;
        int byteread = 0;
        try {
            //文件存储地址
            String path = "src/main/resources/file/filespaths/";
            URL url = new URL(file_url);
            File uploadDir = new File(path);
            //验证存储路径是否存在，不存在则自动创建文件夹
            if ( !uploadDir.exists()){  uploadDir.mkdirs(); }
            //采用时间戳对下载文件命名
            String timeStr =new Date().getTime()+"";
            String newFileName =timeStr+"u";
            //通过路径获取文件后缀
            String extName =  "mp4";
            String saveUrl = path + newFileName+"."+extName;

            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(saveUrl);
            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            fs.close();
            inStream.close();
            res = saveUrl;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
